import React, { useState, useEffect } from 'react';
import { Button, Table, Space, Image, Card, Input, Form, Modal, message, Upload, DatePicker, Select, InputNumber, Tag } from 'antd';
import { PlusOutlined, SearchOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { ConfigProvider } from 'antd';
import locale from 'antd/locale/zh_CN';
import type { UploadFile } from 'antd/es/upload/interface';
import {
  VARIETY_SHOW_STATUS,
  type VarietyShowInfoDetail,
  getVarietyShowInfoPage,
  addVarietyShowInfo,
  updateVarietyShowInfo,
  deleteVarietyShowInfo,
} from '@/services/VarietyShowInfo';
import { uploadFile } from '@/services/FileService';
import styles from './index.less';
import { famousPersonId } from '@/services';
import dayjs from 'dayjs';

const { TextArea } = Input;

const VarietyWorks: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<VarietyShowInfoDetail[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | undefined>();
  const [posterFile, setPosterFile] = useState<UploadFile[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');

  // 加载数据
  const loadData = async (page = pagination.current, pageSize = pagination.pageSize) => {
    try {
      setLoading(true);
      const values = await searchForm.validateFields();
      const response = await getVarietyShowInfoPage({
        pageCurrent: page,
        pageSize: pageSize,
        famousPersonId: famousPersonId,
        keyword: values.keyword,
        status: values.status,
      });
      setData(response.list);
      setPagination({
        current: page,
        pageSize: pageSize,
        total: response.totalCount,
      });
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  // 处理文件上传
  const handleFileUpload = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      const fileId = await uploadFile(file);
      onSuccess({
        uid: fileId.toString(),
        name: file.name,
        status: 'done',
        url: `/api/file/play/${fileId}`,
      });
      message.success('上传成功');
    } catch (error) {
      onError(error);
      message.error('上传失败');
    }
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  }

  // 列定义
  const columns = [
    {
      title: '综艺名称',
      dataIndex: 'title',
      key: 'title',
      width: '15%',
      render: (text: string) => (
        <span style={{ color: '#1890ff', fontWeight: 500 }}>{text}</span>
      ),
    },
    {
      title: '期数名称',
      dataIndex: 'periodName',
      key: 'periodName',
      width: '15%',
    },
    {
      title: '海报',
      dataIndex: 'poster',
      key: 'poster',
      width: '10%',
      render: (poster: number) => (
        poster ? (
          <Image
            src={`/api/file/play/${poster}`}
            alt="海报"
            width={60}
            height={60}
            style={{ objectFit: 'cover', borderRadius: 4 }}
            preview={{
              mask: '预览',
              maskClassName: styles.previewMask,
            }}
          />
        ) : '-'
      ),
    },
    {
      title: '类型',
      dataIndex: 'genre',
      key: 'genre',
      width: '12%',
      render: (genre: string) => {
        if (!genre) return '-';
        return (
          <Space size={[0, 4]} wrap>
            {genre.split(/[,，、]/g).map((item, index) => (
              <Tag color="green" key={index}>{item.trim()}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '期数',
      dataIndex: 'period',
      key: 'period',
      width: '8%',
      render: (period: number, record: VarietyShowInfoDetail) => (
        <span style={{ color: '#722ed1', fontWeight: 500 }}>
          {`${period}/${record.sumPeriod || '?'}`}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '8%',
      render: (status: string) => {
        const statusObj = Object.values(VARIETY_SHOW_STATUS).find(item => item.value === status);
        const colorMap = {
          'WAITING_PLAY': 'orange',
          'PLAYING': 'green',
          'FINISHED': 'blue',
          'UNKNOWN': 'default',
        };
        return statusObj ? (
          <Tag color={colorMap[status as keyof typeof colorMap] || 'default'}>
            {statusObj.label}
          </Tag>
        ) : '-';
      },
    },
    {
      title: '标签',
      dataIndex: 'tags',
      key: 'tags',
      width: '15%',
      render: (tags: string) => {
        if (!tags) return '-';
        return (
          <Space size={[0, 4]} wrap>
            {tags.split(/[,，、]/g).map((tag, index) => (
              <Tag color="purple" key={index}>{tag.trim()}</Tag>
            ))}
          </Space>
        );
      },
    },
    {
      title: '简介',
      dataIndex: 'description',
      key: 'description',
      width: '20%',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      width: '12%',
      render: (_: any, record: VarietyShowInfoDetail) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Button type="link" danger onClick={() => handleDelete(record.id)}>删除</Button>
        </Space>
      ),
    },
  ];

  // 渲染搜索表单
  const renderSearchForm = () => (
    <div className={styles.toolbarContent}>
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        className={styles.searchForm}
      >
        <Form.Item name="keyword">
          <Input
            placeholder="请输入综艺名称或简介"
            allowClear
            prefix={<SearchOutlined />}
          />
        </Form.Item>
        <Form.Item name="status">
          <Select
            placeholder="状态"
            style={{ width: 120 }}
            allowClear
            options={Object.values(VARIETY_SHOW_STATUS)}
          />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
        <Form.Item>
          <Button onClick={handleReset}>重置</Button>
        </Form.Item>
        <Form.Item>
          <Space style={{ marginLeft: 20 }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => {
                setEditingId(undefined);
                form.resetFields();
                setPosterFile([]);
                setModalVisible(true);
              }}
            >
              添加综艺
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );

  // 渲染表单模态框
  const renderModal = () => (
    <Modal
      title={editingId ? '编辑综艺' : '新增综艺'}
      open={modalVisible}
      onCancel={handleCancel}
      footer={null}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="title"
          label="综艺名称"
          rules={[{ required: true, message: '请输入综艺名称' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="periodName"
          label="期数名称"
          rules={[{ required: true, message: '请输入期数名称' }]}
        >
          <Input maxLength={100} />
        </Form.Item>

        <Form.Item
          name="genre"
          label="类型"
        >
          <Input maxLength={50} placeholder="如：真人秀、脱口秀等" />
        </Form.Item>

        <Form.Item
          name="releaseDate"
          label="首播日期"
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="period"
          label="期数"
          rules={[{ required: true, message: '请输入期数' }]}
        >
          <InputNumber min={1} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="sumPeriod"
          label="总期数"
        >
          <InputNumber min={1} style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="description"
          label="简介"
        >
          <TextArea rows={4} maxLength={500} showCount />
        </Form.Item>

        <Form.Item
          name="tags"
          label="标签"
        >
          <Input placeholder="多个标签用逗号、顿号分隔" maxLength={100} />
        </Form.Item>

        <Form.Item
          name="poster"
          label="海报"
        >
          <Upload
            listType="picture-card"
            fileList={posterFile}
            onChange={({ fileList }) => setPosterFile(fileList)}
            customRequest={handleFileUpload}
            maxCount={1}
            onPreview={handlePreview}
          >
            {posterFile.length === 0 && '+ 上传海报'}
          </Upload>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select
            options={Object.values(VARIETY_SHOW_STATUS).filter(item => item.value)}
            placeholder="请选择状态"
          />
        </Form.Item>

        <Form.Item
          name="language"
          label="语言"
        >
          <Input maxLength={20} placeholder="如：国语" />
        </Form.Item>

        <Form.Item label="播放源信息">
          <Form.List name="playSourceInfo">
            {(fields, { add, remove }) => (
              <div className={styles.sourceList}>
                {fields.map(({ key, name, ...restField }) => (
                  <div key={key} className={styles.sourceItem}>
                    <div className={styles.sourceContent}>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceName']}
                        style={{ marginBottom: 12 }}
                      >
                        <Input placeholder="播放源名称（如：爱奇艺）" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'sourceUrl']}
                        style={{ marginBottom: 0 }}
                      >
                        <Input.TextArea
                          placeholder="播放源地址"
                          autoSize={{ minRows: 1, maxRows: 3 }}
                        />
                      </Form.Item>
                    </div>
                    <Button
                      type="link"
                      className={styles.deleteButton}
                      onClick={() => remove(name)}
                      icon={<MinusCircleOutlined />}
                      danger
                    />
                  </div>
                ))}
                <Button
                  type="dashed"
                  onClick={() => add()}
                  block
                  icon={<PlusOutlined />}
                  className={styles.addButton}
                >
                  添加播放源
                </Button>
              </div>
            )}
          </Form.List>
        </Form.Item>

        <Form.Item className={styles.modalFooter}>
          <Space>
            <Button onClick={handleCancel}>取消</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );

  // 其他处理函数...
  const handleSubmit = async (values: any) => {
    try {
      const playSourceInfo = values.playSourceInfo?.filter((source: any) =>
        source && (source.sourceName?.trim() || source.sourceUrl?.trim())
      ) || [];

      const submitData = {
        ...values,
        famousPersonId,
        releaseDate: values.releaseDate ? values.releaseDate.format('YYYY-MM-DD') : null,
        poster: posterFile.length > 0 ? posterFile[0]?.response?.uid || posterFile[0]?.uid : null,
        playSourceInfo,
      };

      if (editingId) {
        await updateVarietyShowInfo({ ...submitData, id: editingId });
        message.success('更新成功');
      } else {
        await addVarietyShowInfo(submitData);
        message.success('添加成功');
      }
      handleCancel();
      loadData();
    } catch (error) {
      message.error('操作失败');
    }
  };

  // 添加搜索处理函数
  const handleSearch = async (values: any) => {
    setPagination(prev => ({ ...prev, current: 1 }));
    loadData(1, 20);
  };

  // 添加表格变化处理函数
  const handleTableChange = (newPagination: any) => {
    loadData(newPagination.current, newPagination.pageSize);
  };

  // 添加取消处理函数
  const handleCancel = () => {
    setModalVisible(false);
    setEditingId(undefined);
    form.resetFields();
    setPosterFile([]);
  };

  // 添加删除处理函数
  const handleDelete = (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个综艺节目吗？删除后无法恢复。',
      okText: '确认',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await deleteVarietyShowInfo([id]);
          message.success('删除成功');
          loadData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 添加编辑处理函数
  const handleEdit = (record: VarietyShowInfoDetail) => {
    setEditingId(record.id);
    form.setFieldsValue({
      ...record,
      releaseDate: record.releaseDate ? dayjs(record.releaseDate) : undefined,
    });

    if (record.poster) {
      setPosterFile([{
        uid: record.poster.toString(),
        name: 'poster',
        status: 'done',
        url: `/api/file/play/${record.poster}`,
      }]);
    } else {
      setPosterFile([]);
    }

    setModalVisible(true);
  };

  // 修改图片预览处理函数
  const handlePreview = async (file: UploadFile) => {
    const resp = file.response
    if (resp) {
      const fileId = resp.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    } else {
      const fileId = file.uid;
      const previewUrl = `/api/file/play/${fileId}`;
      setPreviewImage(previewUrl);
      setPreviewOpen(true);
    }
  };

  return (
    <ConfigProvider locale={locale}>
      <div className={styles.container}>
        <Card title="综艺节目管理">
          <div className={styles.toolbar}>
            {renderSearchForm()}
          </div>
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={loading}
            scroll={{ y: 'calc(100vh - 380px)', scrollToFirstRowOnChange: false }}
            pagination={{
              ...pagination,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条`,
              pageSizeOptions: ['20', '50', '100'],
            }}
            onChange={handleTableChange}
          />
          {renderModal()}
          {previewImage && (
            <Image
              style={{ display: 'none' }}
              preview={{
                visible: previewOpen,
                src: previewImage,
                onVisibleChange: (visible) => {
                  setPreviewOpen(visible);
                  if (!visible) {
                    setPreviewImage('');
                  }
                },
              }}
            />
          )}
        </Card>
      </div>
    </ConfigProvider>
  );
};

export default VarietyWorks; 